package part2;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: shaochong
 * @Date: 2021/8/15
 * @Description: 给定一个二叉树的根节点 root ，返回它的 中序 遍历。
 */
public class Solution94 {
    private class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
    }

    // 递归算法
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        dfs(list, root);
        return list;
    }

    public void dfs(List<Integer> ans, TreeNode root) {
        if (root != null) {
            dfs(ans, root.left);
            ans.add(root.val);
            dfs(ans, root.right);
        }
    }

    // 非递归
    public List<Integer> inorderTraversal2(TreeNode root) {
        Deque<TreeNode> stk = new LinkedList<>();
        List<Integer> res = new ArrayList<Integer>();
        while (root != null || !stk.isEmpty()) {
            while (root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }

}
